﻿using IServices;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using NDLS.WebApi.Model.ModelVM;
using RZWH.WebApi.Model;
using RZWH.WebApi.Model.DBmodels;
using RZWH.WebApi.Services.Encrypted;
using RZWH.WebApi.Services.JWT;

namespace Services
{
    public class UserService : IUserService
    {
        private readonly EncryptedPwd _encryptedPwd = new EncryptedPwd();
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly string _secretKey; // 密钥

        public UserService(IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
        {
            _secretKey = configuration["pwdSecretKey"] ?? "1234567812345678"; // 从配置文件中获取密钥
            _httpContextAccessor = httpContextAccessor;
        }

        public User GetUserInfo()
        {
            HttpContext httpContext = _httpContextAccessor.HttpContext;
            string tokenValue = httpContext.Request.Cookies["Token"];
            return jwtHelper.DeserializeJwt(tokenValue);
        }

        public MsgRes Login(string username, string password)
        {
            using (var context = new FluffypawmediaContext())
            {
                var user = context.Users.FirstOrDefault(u => u.UserName == username);
                if (user == null)
                {
                    // 用户不存在的情况
                    return new MsgRes { Status = "Error", Msg = "用户名或密码不正确" };
                }
                else
                {
                    // 解码Base64的存储密码
                    byte[] storedPasswordBytes = Convert.FromBase64String(user.UserPassword ?? "");

                    // 提取IV和加密的密码部分
                    byte[] iv = storedPasswordBytes.Take(16).ToArray();

                    // 使用存储的IV和密钥对用户提供的密码进行加密
                    string encryptedUserPassword = _encryptedPwd.EncryptPassword(password, _secretKey, iv);

                    // 将加密后的用户提供的密码与存储的密码进行比较
                    if (encryptedUserPassword == Convert.ToBase64String(storedPasswordBytes))
                    {
                        var token = jwtHelper.IssueJwt(user);
                        HttpContext httpContext = _httpContextAccessor.HttpContext;
                        httpContext?.Response.Cookies.Append("Token", token, new CookieOptions
                        {
                            Expires = DateTime.Now.AddMinutes(20)
                        });
                        // 密码正确，返回成功消息
                        return new MsgRes { Status = "Success", Msg = "登录成功", Token = token, Role = user.RoleId, UserInfo = jwtHelper.DeserializeJwt(token) };
                    }
                    else
                    {
                        // 密码不正确，返回通用错误消息
                        return new MsgRes { Status = "Error", Msg = "用户名或密码不正确" };
                    }
                }
            }
        }

        public MsgRes Register(string username, string password)
        {
            using (var context = new FluffypawmediaContext())
            {
                var user = context.Users.FirstOrDefault(u=> u.UserName == username);
                if (user != null)
                {
                    return new MsgRes { Status = "Error", Msg = "用户名已存在" };
                }
                else
                {
                    // 生成随机的IV
                    byte[] iv = _encryptedPwd.GenerateRandomIV();

                    // 使用AES128、CBC模式和PKCS7填充来加密密码
                    string Password = _encryptedPwd.EncryptPassword(password, _secretKey, iv);

                    User newUser = new User { UserName = username, UserPassword = Password, RoleId = 1  };
                    try
                    {
                        // 将用户对象添加到数据库
                        context.Users.Add(newUser);
                        context.SaveChanges(); // 保存更改到数据库
                        return new MsgRes { Status = "Success", Msg = "注册成功" };
                    }
                    catch
                    {
                        return new MsgRes { Status = "Error", Msg = "注册失败" };
                    }
                }
            }
        }
    }
}
